package com.learing.handler.realChat;

import com.learing.message.MessageRequestPacket;
import com.learing.message.MessageResponsePacket;
import com.learing.session.Session;
import com.learing.utils.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;

public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket messageRequestPacket) {
//        MessageResponsePacket messageResponsePacket = receiveMessage(messageRequestPacket);
//        ByteBuf responseByteBuf = PacketCodeC.INSTANCE.encode(ctx.alloc(), messageResponsePacket);
        receiveMessage(messageRequestPacket, ctx);
    }

    /**
     * 处理消息
     *
     * @param messageRequestPacket
     * @param ctx
     */
    private void receiveMessage(MessageRequestPacket messageRequestPacket, ChannelHandlerContext ctx) {

        // 1.拿到消息发送方的会话信息
        Session session = SessionUtil.getSession(ctx.channel());

        // 2.通过消息发送方的会话信息构造要发送的消息
        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        messageResponsePacket.setFromUserId(session.getUserId());
        messageResponsePacket.setFromUserName(session.getUserName());
        messageResponsePacket.setMessage(messageRequestPacket.getMessage());
        // 3.拿到消息接收方的 channel
        Channel toUserChannel = SessionUtil.getChannel(messageRequestPacket.getToUserId());

        // 4.将消息发送给消息接收方
        if (toUserChannel != null && SessionUtil.hasLogin(toUserChannel)) {
            toUserChannel.writeAndFlush(messageResponsePacket);
        } else {
            System.err.println("[" + messageRequestPacket.getToUserId() + "] 不在线，发送失败!");
        }
        // 处理消息
        System.err.println("用户 " + session.getUserId() + " 对用户" + messageRequestPacket.getToUserId() + " 说:" + messageRequestPacket.getMessage());

    }
}